import axios from "axios";
// import browser from "../common/browser";
import md5 from "js-md5";
import { Notification } from "element-ui";
import Router from "../router/index.js";
// import qs from "qs";
// 创建 axios 实例
let http = axios.create({
  // baseURL: process.env.VUE_APP_URL || process.env.apiUrl || '/api/',
  // headers: {'Content-Type': 'application/json'},
  // baseURL: process.env.NODE_ENV === 'production' ?
  timeout: 60000,
});

// 设置 post、put 默认 Content-Type
http.defaults.headers.post["Content-Type"] = "application/json";
// "application/x-www-form-urlencoded;charset=UTF-8";
http.defaults.headers.put["Content-Type"] = "application/json";

// 添加请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    let language = localStorage.getItem("locale");
    // if (localStorage.getItem("token")) {
    //   config.headers.Authorization = localStorage.getItem("token");
    // }
    if (config.method === "post") {
      let data = JSON.parse(config.data);
      if (
        config.url.indexOf("bapi.kuke.com") != -1 ||
        config.url.indexOf("test2b.kuke.com") != -1
      ) {
        config.data = JSON.stringify({
          versionId: -1, //版本ID
          version: "pc", //版本号
          channelId: -1, // 渠道ID
          device: "pc", // 设备号
          useType: 3, //平台信息 3.pc
          token: token == null ? "" : token,
          language: language === "en" ? "EN" : "CN",
          ...data,
        });
      } else if (config.url.indexOf("data-api.kuke.com") != -1) {
        let apiKey = "8c314cd5d048a7ed787282daa26fc517";
        let apiSecret = "6e68662e-0cca-468e-a5b4-e2c4812ddc32";
        let time = +new Date();
        config.data = {
          apiKey: apiKey,
          sign: md5(apiKey + apiSecret + time) + time,
          snid: "1",
          userId: "1",
          ...data,
        };
      }
    } else if (config.method === "get") {
      // && browser.isIE
      // 给GET 请求后追加时间戳， 解决IE GET 请求缓存问题
      // let symbol = config.url.indexOf("?") >= 0 ? "&" : "?";
      // config.url += symbol + "_=" + Date.now();
      if (
        config.url.indexOf("bapi.kuke.com") != -1 ||
        config.url.indexOf("test2b.kuke.com") != -1
      ) {
        config.params = {
          versionId: -1, //版本ID
          version: "pc", //版本号
          channelId: -1, // 渠道ID
          device: "pc", // 设备号
          useType: 3, //平台信息 3.pc
          token: token == null ? "" : token,
          language: language === "en" ? "EN" : "CN",
          ...config.params,
        };
      } else if (config.url.indexOf("data-api.kuke.com") != -1) {
        let apiKey = "8c314cd5d048a7ed787282daa26fc517";
        let apiSecret = "6e68662e-0cca-468e-a5b4-e2c4812ddc32";
        let time = +new Date();
        config.params = {
          apiKey: apiKey,
          sign: md5(apiKey + apiSecret + time) + time,
          snid: "1",
          userId: "1",
          // JSON.parse(localStorage.getItem("userInfo")).userId,
          ...config.params,
        };
      }
      // config.paramsSerializer = function(params) {
      //   return Qs.stringify(params, { arrayFormat: 'repeat' })
      // }
    }
    // console.log(config.headers)
    // if (config.headers.Content-Type == 'application/x-www-form-urlencoded;charset=UTF-8'){
    //   config.data = Qs.stringify(config.data)
    // }
    // 请求发送前进行处理
    return config;
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    // console.log(response.data.code)
    if (
      response.data.code === 1000004 &&
      localStorage.getItem("loginStatu") == "true"
    ) {
      alert("登录超时,请重新登录！");
      // Notification.error({
      //   title: "抱歉",
      //   message: "登录超时，请检查登录状态",
      //   duration: 6000,
      // });
      window.localStorage.setItem("loginStatu", false);
      window.localStorage.removeItem("token");
      // window.localStorage.removeItem("userInfo");
      window.location.reload();
    } else if (response.data.code === 1000004) {
      Notification.error({
        showClose: true,
        title: "抱歉",
        message: "此功能需要登录权限,请登录后再试！",
        duration: 3000,
      });
    }
    let { data } = response;
    return data;
  },
  (error) => {
    let info = {};
    if (!error.response) {
      info = {
        code: 5000,
        msg: "Network Error",
      };
      if (error.message == "Network Error") {
        Router.push("/networkError");
      }
    } else {
      let { status, statusText, data } = error.response;
      // 此处整理错误信息格式
      info = {
        code: status,
        data: data,
        msg: statusText,
      };
    }
    return Promise.reject(info);
  }
);

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function () {
  return http;
}
